<template>
  <div class="app-container">
    <div class="filter-container">
      <SearchOptionClass :class-id="listQuery.id" @setSearchClassId="searchClassId" />
      <el-select v-model="listQuery.year" placeholder="年级" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in yearOption" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.quarter" placeholder="季度" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in quarterOption" :key="key" :label="value" :value="key" />
      </el-select>
      <el-select v-model="listQuery.semester" placeholder="学期" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in semesterOption" :key="key" :label="value" :value="key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年" align="center" width="60">
        <template slot-scope="{row}">
          <span>{{ row.year }}</span>
        </template>
      </el-table-column>
      <el-table-column label="季度" align="center">
        <template slot-scope="{row}">
          <span>{{ quarterOption[row.quarter] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学期" prop="semester" align="center" sortable="custom" :class-name="getSortClass('semester')">
        <template slot-scope="{row}">
          <span>{{ semesterOption[row.semester] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级简称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.short_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" align="center" sortable="custom" :class-name="getSortClass('sort')">
        <template slot-scope="{row}">
          <span>{{ row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否App显示" align="center">
        <template slot-scope="{row}">
          <span>{{ isShowOption[row.is_show] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否删除" align="center">
        <template slot-scope="{row}">
          <span :class="{redActive:row.is_del==1}">{{ row.is_del ==0?'否':'是' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级类型" align="center">
        <template slot-scope="{row}">
          <span>{{ classTypeOptions[row.type] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">
            删除
          </el-button>
          <el-button type="success" size="mini" @click="getClassUser(row)">
            学员信息
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item label="年级" prop="year">
          <el-select v-model="temp.year" class="filter-item">
            <el-option v-for="item in yearOption" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="季度" prop="quarter">
          <el-select v-model="temp.quarter" class="filter-item">
            <el-option v-for="(value,key) in quarterOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-select v-model="temp.semester" class="filter-item">
            <el-option v-for="(value,key) in semesterOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="班级简称" prop="short_name">
          <el-input v-model="temp.short_name" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="temp.sort" />
        </el-form-item>
        <el-form-item label="是否App显示">
          <el-select v-model="temp.is_show" prop="is_show" class="filter-item">
            <el-option v-for="(value,key) in isShowOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否删除">
          <el-select v-model="temp.is_del" prop="is_del" class="filter-item">
            <el-option v-for="(value,key) in isdelOption" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级类型">
          <el-select v-model="temp.type" prop="type" class="filter-item">
            <el-option v-for="(value,key) in classTypeOptions" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { classPage, classUpdate, classDelete } from '@/api/class'
import waves from '@/directive/waves' // waves directive
import { isInteger } from '@/utils/validate'
import { notifySuccess, formatJson, my_confirm, listQueryFilter } from '@/utils/tool'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import SearchOptionClass from '@/components/SearchOption/class'

export default {
  name: 'ClassPage',
  components: { Pagination, SearchOptionClass },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        querySort: '-id',
        year: undefined,
        quarter: undefined,
        semester: undefined,
        name: undefined,
        is_show: undefined,
        type: undefined
      },
      isdelOption: {
        0: '否',
        1: '是'
      },
      isShowOption: {
        0: '不显示',
        1: '显示'
      },
      classTypeOptions: { 1: '默认', 2: 'iEMBA班级', 3: 'TiEMBA班级' },
      yearOption: [2023, 2022, 2021, 2020, 2019, 2018, 2017, 2016, 2015, 2014, 2013, 2012, 2011, 2010], // 一级菜单的下拉列表
      quarterOption: { 1: '春季班', 2: '秋季班' },
      semesterOption: { 1: '第一学期', 2: '第二学期', 3: '第三学期', 4: '第四学期' },
      temp: {
        id: undefined,
        year: '',
        quarter: '',
        semester: '',
        name: '',
        short_name: '',
        sort: '',
        is_show: '',
        is_del: '',
        type: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        year: [{ required: true, message: '年级必填且是数字', trigger: 'change' }, { validator: isInteger, trigger: 'blur' }],
        quarter: [{ required: true, message: '季度必填且是数字', trigger: 'change' }, { validator: isInteger, trigger: 'blur' }],
        semester: [{ required: true, message: '学期必填且是数字', trigger: 'change' }, { validator: isInteger, trigger: 'blur' }],
        name: [{ required: true, message: '班级名称必填', trigger: 'change' }],
        short_name: [{ required: true, message: '班级简称必填', trigger: 'change' }],
        sort: [{ required: true, message: '排序必填且为数字', trigger: 'change' }, { validator: isInteger, trigger: 'blur' }],
        is_show: [{ required: true, message: '是否app显示必填且为数字', trigger: 'change' }, { validator: isInteger, trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery = listQueryFilter(this.listQuery)
      classPage(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.page
        this.listLoading = false
      })
    },
    getClassUser(row) {
      this.$router.push({
        path: '/class/user',
        query: {
          id: row.id
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'sort') {
        this.sortByID(order, prop)
      }
    },
    sortByID(order, prop) {
      if (order === 'ascending') {
        this.listQuery.querySort = '+' + prop
      } else {
        this.listQuery.querySort = '-' + prop
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        year: '',
        quarter: '',
        semester: '',
        name: '',
        short_name: '',
        sort: '',
        is_show: '',
        is_del: '',
        type: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          classUpdate(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp.id = row.id
      this.temp.year = parseInt(row.year)
      this.temp.name = row.name
      this.temp.quarter = row.quarter
      this.temp.semester = row.semester
      this.temp.short_name = row.short_name
      this.temp.sort = row.sort
      this.temp.is_show = row.is_show
      this.temp.is_del = row.is_del
      this.temp.type = row.type
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          classUpdate(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
          })
        }
      })
    },
    handleDelete(row, index) {
      my_confirm(this, () => {
        classDelete({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['年', '季度', '学期', '班级名称', '班级简称', '小到大', '是否app显示', '是否删除', '班级类型']
        const filterVal = ['year', 'quarter', 'semester', 'name', 'short_name', 'sort', 'is_show', 'is_del', 'type']
        const data = formatJson(this, filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '班级表'
        })
        this.downloadLoading = false
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.querySort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    searchClassId: function(data) { // 触发子组件城市选择-选择城市的事件
      this.listQuery.id = data.classId // 改变了父组件的值
    }
  }
}
</script>

